package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.intercepror.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserLocationApi userLocationApi;
    @DubboReference
    private VisitorsApi visitorsApi;

    /**
     * 今日佳人
     *
     * @return
     */
    public TodayBest todayBest() {
        //1.获取当前用户id
        Long toUserId = UserHolder.getUserId();
        //2.调用api查询推荐用户数据  RecommendUser
        RecommendUser ru = recommendUserApi.queryWithMaxScore(toUserId);
        //对应新用户没有推荐数据
        if (ru == null) {
            ru = new RecommendUser();
            ru.setUserId(1l);//模拟推荐的用户id
            ru.setScore(99d);//模拟推荐的缘分值
        }
        //3.根据查询出的推荐表中的数据里面的今日佳人id查询出UserInfo信息
        UserInfo userInfo = userInfoApi.findById(ru.getUserId());
        //4.根据UserInfo和RecommendUser构造返回值vo
        TodayBest vo = TodayBest.init(userInfo, ru);
        //5.返回
        return vo;
    }

    /**
     * 查询首页推荐的用户列表（分页）
     */
    public PageResult recommendation(Integer page, Integer pagesize) {
        //1.获取当前用户id
        Long toUserId = UserHolder.getUserId();
        //2.调用api查询当前页的数据列表---List（RecommendUser）
        List<RecommendUser> list = recommendUserApi.queryRecommendUserList(toUserId, page, pagesize);
        //3.判断集合数据是否为空，构造默认假数据
        if (list == null || list.isEmpty()) {
            list = defaultList();
        }
        //4.将ListRecommendUser转化成List<TodayBeat>
        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser user : list) {//遍历表（大数据分析丽人）中的数据
            UserInfo info = userInfoApi.findById(user.getUserId());//将其中丽人的id取出，查询丽人的用户信息
            TodayBest vo = TodayBest.init(info, user);//把丽人信息转化成需要响应页面的vo
            vos.add(vo);//将所有佳人信息添加到Vos集合
        }
        //5.构造返回
        return new PageResult(page,pagesize,0l,vos);
    }

    private List<RecommendUser> defaultList() {
        List<RecommendUser> list = new ArrayList<>();
        //构造默认推荐数据，企业中按照项目经理要求
        for (int i = 1; i <= 10; i++) {
            RecommendUser ru = new RecommendUser();
            ru.setUserId((long) i); //模拟推荐的用户id
            ru.setScore(95D); //模拟推荐的评分
            list.add(ru);
        }
        return list;
    }

    //查询佳人详情
    public TodayBest personalInfo(Long userId) {
        //a:完成业务逻辑
        //1.查询用户的用户信息
        UserInfo userInfo = userInfoApi.findById(userId);
        //2.查询推荐用户数据（获取缘分值）
        Long toUserId = UserHolder.getUserId();
        RecommendUser user = recommendUserApi.queryByUserId(userId, toUserId);
        //b:保存来访记录
        Visitors visitors = new Visitors();
        visitors.setUserId(userId);
        visitors.setVisitorUserId(UserHolder.getUserId());
        visitors.setFrom("首页");
        visitors.setDate(System.currentTimeMillis());
        String visitDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        visitors.setVisitDate(visitDate);
        visitors.setScore(user.getScore());
        visitorsApi.save(visitors);
        //c:
        //构造返回的vo对象
        return TodayBest.init(userInfo, user);
    }

    //查询陌生人问题
    public String strangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        return question == null ? "你喜欢JAVA不？" : question.getTxt();
    }

    /**
     * {"userId":106,"huanXinId":"hx106","nickname":"黑马小妹",
     * "strangerQuestion":"你喜欢去看蔚蓝的大海还是去爬巍峨的高山？",
     * "reply":"我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~"}
     */
    //回复陌生人问题---向对方发送一条系统消息
    public void reply(Long userId, String reply) {
        Map map = new HashMap();
        map.put("userId", UserHolder.getUserId());//发送者id
        map.put("huanXinId", "hx" + UserHolder.getUserId());//发送人的环信id
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        map.put("nickname", userInfo.getNickname());//发送人的昵称
        //陌生人问题
        String questions = strangerQuestions(userId);
        map.put("strangerQuestion", questions);
        //回复的内容
        map.put("reply", reply);
        //发布的消息JSON字符串
        String message = JSON.toJSONString(map);
        //发布消息
        huanXinTemplate.sendMsg("hx"+userId,message);//环信的账户，发布的消息JSON字符串

    }

    //查询附近的人
    public List<NearUserVo> distance(String gender, String distance) {
        Long userId = UserHolder.getUserId();
        //1.调用API查询，附近人的id集合，包含自己的id，List<userId>
        List<Long> list = userLocationApi.searchNear(userId, distance);
        //2.一个userId，构建一个NearUserVo
        Map<Long, UserInfo> map = userInfoApi.findByIds(list);
        List<NearUserVo> vos = new ArrayList<>();
        for (Long id : list) {
            if (userId == id) {
                continue;
            }
            UserInfo userInfo = map.get(id);
            if (!StringUtils.isEmpty(gender)) {//根据性别筛选，不为空时
                if (!gender.equals(userInfo.getGender())) {//性别和查询的不一致
                    break;
                }
            }
            NearUserVo vo = NearUserVo.init(userInfo);
            vos.add(vo);
        }
        return vos;
    }
}
